In C and C++, pointers and arrays have a close relationship, and you can use pointers to access and manipulate memory in a manner similar to arrays. This is often referred to as "using pointers as arrays." Here's a brief overview:
-
You can initialize a pointer to the first element of an array, effectively making it point to the beginning of a contiguous block of memory.
int arr[5] = {1, 2, 3, 4, 5}; int *ptr = arr; // 'ptr' now points to the first element of 'arr'
-
You can use pointer arithmetic to navigate through the elements of the array.
// Accessing elements using pointer arithmetic printf("%d\n", *ptr); // Prints the value of the first element printf("%d\n", *(ptr + 1)); // Prints the value of the second element
-
Incrementing or decrementing the pointer advances or retreats to the next or previous element.
ptr++; // Move to the next element
-
You can use array subscript notation with pointers, which is equivalent to using the array directly.
printf("%d\n", ptr[2]); // Prints the value of the third element
Here's a simple example demonstrating the use of a pointer as an array:
#include <stdio.h> int main() { int arr[5] = {10, 20, 30, 40, 50}; // Using a pointer to traverse the array int *ptr = arr; for (int i = 0; i < 5; ++i) { printf("Element %d: %d\n", i, *(ptr + i)); } return 0; }
This program uses a pointer ptr
to iterate over the elements of the array arr
and prints their values. The syntax *(ptr + i)
is equivalent to arr[i]
, demonstrating how pointers can be used to access array elements.